<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace cmf\controller;

use think\Db;
use app\admin\model\ThemeModel;
use think\View;

use app\hotel\model\HotelSystermModel;
class HomeBaseController extends BaseController
{

    public function _initialize()
    {

        // 监听home_init
        hook('home_init');
        parent::_initialize();
        $siteInfo = cmf_get_site_info();
        $this->auth();//判断是否通过授权
        View::share('site_info', $siteInfo);
        $s = $this->SelfShare();
        View::share('s', $s);
    }

    public function auth(){
        $access_token = session('access_token');
        if($access_token == "" || time() - $access_token['expires_time'] >0){
            $this->get_oauth_userinfo();
        }


    }

   /*&
    *  获取用户信息
    */
    public function get_oauth_userinfo(){

        if (empty(config('appID'))){
            return error(-2, '公众号未设置 appId 或 secret.');
        }
        $state = 'hotel-' . time();
        $callback =   urlencode("http://www.loveff.xin/hotel/Auth/callBack.html");
        $forward = $this->getOauthUserInfoUrl($callback, $state);
        header('Location: ' . $forward);
    }

    public function getOauthUserInfoUrl($callback, $state = '') {

       return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
            .config('appID').'&redirect_uri='.$callback.'&response_type=code&scope=snsapi_userinfo&&state='.$state.'#wechat_redirect';

    }

    /**
     * 分享功能
     */
    public   function SelfShare($debug = 'true')
    {
        $HotelSysterm = new HotelSystermModel();
        $jsapi_ticket =$HotelSysterm->where(['id'=>1])->find();
        $jsapi_ticket = $this->getJsapi_ticket($jsapi_ticket);
        $random = $this->random(10);
        $time = time();

        $signature = [
            'noncestr' => $random,
            'jsapi_ticket' => json_decode($jsapi_ticket)->ticket,
            'timestamp' => $time,
            'url' => 'http://www.loveff.xin/hotel/List/index.html',

        ];
        ksort($signature);
        foreach ($signature as $k => &$v) {
            $v = $k . '=' . $v;
        }
        $appid = config('appID');
        $tiaourl =  config('tiao_url');
        $signature = sha1(implode('&', $signature));

        $res['tiaourl'] = $tiaourl;
        $res['appid']  = $appid;
        $res['signature']  = $signature;
        $res['timestamp']  = $time;
        $res['nonceStr']  = $random;
        return $res;

        /*
           $wxJSDK = <<<str
                   <script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
                    <script type="text/javascript">
                           wx.config({
                               debug: true,
                               appId: $appid,
                               timestamp: "{$time}",
                               nonceStr: "{$random}",
                               signature: "{$signature}",
                               jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline']
                           });
                           wx.ready(function () {
                               wx.onMenuShareTimeline({
                                   title: '酒店预定',
                                   link: $tiaourl,
                                   imgUrl: "http://www.loveff.xin/upload/hotel/20180606/b3ed1c5ff9eb3513712f0d3fcd8dadc3.jpg",
                                   success: function () {

                                   },
                               });
                               wx.onMenuShareAppMessage({
                                   title: '酒店预定',
                                   link: "<?php echo config('tiao_url')?>",
                                   imgUrl: "http://www.loveff.xin/upload/hotel/20180606/b3ed1c5ff9eb3513712f0d3fcd8dadc3.jpg",
                                   success: function () {

                                   },
                                   cancel: function () {

                                   }
                               });
                           })
                   </script>
   str;
           echo $wxJSDK;*/
    }

    /**
     * 获取sapi_ticket
     */
    public function getJsapi_ticket($activeData)
    {
        $HotelSysterm = new HotelSystermModel();

        if (!$activeData['jsapi_ticket'] || empty(json_decode($activeData['jsapi_ticket'])->ticket) || (time() - json_decode($activeData['jsapi_ticket'])->time) > (60 * 60 * 2)) {
            if (!$activeData['js_access_token'] || empty(json_decode($activeData['js_access_token'])->ticket) || (time() - json_decode($activeData['js_access_token'])->time) > (60 * 60 * 2)) {
                $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $activeData['js_appid'] . '&secret=' . $activeData['js_appsecret'];
                $AKresponse = $this->postCurl($url);

                $AKresult = json_decode($AKresponse);
                $AKdata = [];
                $AKdata['access_token'] = $AKresult->access_token;
                $AKdata['time'] = time();
                $activeData['js_access_token'] = json_encode($AKdata);

                $HotelSysterm->isUpdate(true)->save(["js_access_token" => $activeData['js_access_token']], ["id" => '1']);
            }

            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . json_decode($activeData['js_access_token'])->access_token . '&type=jsapi';
            $TKresponse = $this->postCurl($url);
            $TKresult = json_decode($TKresponse);
            $TKdata = [];
            $TKdata['ticket'] = $TKresult->ticket;
            $TKdata['time'] = time();
            $TKdata = json_encode($TKdata);

            $HotelSysterm->isUpdate(true)->save(["jsapi_ticket" => $TKdata], ["id" => '1']);
        } else {
            $TKdata = $activeData['jsapi_ticket'];
        }
        return $TKdata;
    }
    /*
     * CURL
     */
    public function postCurl($url, $option=array(), $header = array(), $type = 'POST',$setopt = 10) {
        $curl = curl_init (); // 启动一个CURL会话
        if($curl !== false){
            curl_setopt ( $curl, CURLOPT_URL, $url ); // 要访问的地址
            curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE ); // 对认证证书来源的检查
            curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE ); // 从证书中检查SSL加密算法是否存在
            curl_setopt ( $curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)' ); // 模拟用户使用的浏览器
            if (! empty ( $option )) {
                curl_setopt ( $curl, CURLOPT_POSTFIELDS, $option ); // Post提交的数据包
            }
            curl_setopt ( $curl, CURLOPT_TIMEOUT, $setopt ); // 设置超时限制防止死循环
            if(empty($header)){
                $header = array();
            }
            curl_setopt ( $curl, CURLOPT_HTTPHEADER, $header ); // 设置HTTP头
            curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // 获取的信息以文件流的形式返回
            curl_setopt ( $curl, CURLOPT_CUSTOMREQUEST, $type );
            curl_getinfo($curl, CURLINFO_HTTP_CODE); // 获取Status Code 正确返回200
            $result = curl_exec ( $curl ); // 执行操作
            curl_close ( $curl ); // 关闭CURL会话
            return $result;
        }else{
            return false;
        }
    }


    function random($length, $numeric = FALSE) {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed{mt_rand(0, $max)};
        }
        return $hash;
    }



    public function _initializeView()
    {
        $cmfThemePath    = config('cmf_theme_path');
        $cmfDefaultTheme = cmf_get_current_theme();

        $themePath = "{$cmfThemePath}{$cmfDefaultTheme}";

        $root = cmf_get_root();
        //使cdn设置生效
        $cdnSettings = cmf_get_option('cdn_settings');
        if (empty($cdnSettings['cdn_static_root'])) {
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$root}/{$themePath}",
                '__STATIC__'   => "{$root}/static",
                '__WEB_ROOT__' => $root
            ];
        } else {
            $cdnStaticRoot  = rtrim($cdnSettings['cdn_static_root'], '/');
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$cdnStaticRoot}/{$themePath}",
                '__STATIC__'   => "{$cdnStaticRoot}/static",
                '__WEB_ROOT__' => $cdnStaticRoot
            ];
        }

        $viewReplaceStr = array_merge(config('view_replace_str'), $viewReplaceStr);
        config('template.view_base', "{$themePath}/");
        config('view_replace_str', $viewReplaceStr);

        $themeErrorTmpl = "{$themePath}/error.html";
        if (file_exists_case($themeErrorTmpl)) {
            config('dispatch_error_tmpl', $themeErrorTmpl);
        }

        $themeSuccessTmpl = "{$themePath}/success.html";
        if (file_exists_case($themeSuccessTmpl)) {
            config('dispatch_success_tmpl', $themeSuccessTmpl);
        }


    }

    /**
     * 加载模板输出
     * @access protected
     * @param string $template 模板文件名
     * @param array $vars 模板输出变量
     * @param array $replace 模板替换
     * @param array $config 模板参数
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        $template = $this->parseTemplate($template);
        $more     = $this->getThemeFileMore($template);
        $this->assign('theme_vars', $more['vars']);
        $this->assign('theme_widgets', $more['widgets']);
        return parent::fetch($template, $vars, $replace, $config);
    }

    /**
     * 自动定位模板文件
     * @access private
     * @param string $template 模板文件规则
     * @return string
     */
    private function parseTemplate($template)
    {
        // 分析模板文件规则
        $request = $this->request;
        // 获取视图根目录
        if (strpos($template, '@')) {
            // 跨模块调用
            list($module, $template) = explode('@', $template);
        }

        $viewBase = config('template.view_base');

        if ($viewBase) {
            // 基础视图目录
            $module = isset($module) ? $module : $request->module();
            $path   = $viewBase . ($module ? $module . DS : '');
        } else {
            $path = isset($module) ? APP_PATH . $module . DS . 'view' . DS : config('template.view_path');
        }

        $depr = config('template.view_depr');
        if (0 !== strpos($template, '/')) {
            $template   = str_replace(['/', ':'], $depr, $template);
            $controller = cmf_parse_name($request->controller());
            if ($controller) {
                if ('' == $template) {
                    // 如果模板文件名为空 按照默认规则定位
                    $template = str_replace('.', DS, $controller) . $depr . $request->action();
                } elseif (false === strpos($template, $depr)) {
                    $template = str_replace('.', DS, $controller) . $depr . $template;
                }
            }
        } else {
            $template = str_replace(['/', ':'], $depr, substr($template, 1));
        }
        return $path . ltrim($template, '/') . '.' . ltrim(config('template.view_suffix'), '.');
    }

    /**
     * 获取模板文件变量
     * @param string $file
     * @param string $theme
     * @return array
     */
    private function getThemeFileMore($file, $theme = "")
    {

        //TODO 增加缓存
        $theme = empty($theme) ? cmf_get_current_theme() : $theme;

        // 调试模式下自动更新模板
        if (APP_DEBUG) {
            $themeModel = new ThemeModel();
            $themeModel->updateTheme($theme);
        }

        $themePath = config('cmf_theme_path');
        $file      = str_replace('\\', '/', $file);
        $file      = str_replace('//', '/', $file);
        $file      = str_replace(['.html', '.php', $themePath . $theme . "/"], '', $file);

        $files = Db::name('theme_file')->field('more')->where(['theme' => $theme])->where(function ($query) use ($file) {
            $query->where(['is_public' => 1])->whereOr(['file' => $file]);
        })->select();

        $vars    = [];
        $widgets = [];
        foreach ($files as $file) {
            $oldMore = json_decode($file['more'], true);
            if (!empty($oldMore['vars'])) {
                foreach ($oldMore['vars'] as $varName => $var) {
                    $vars[$varName] = $var['value'];
                }
            }

            if (!empty($oldMore['widgets'])) {
                foreach ($oldMore['widgets'] as $widgetName => $widget) {

                    $widgetVars = [];
                    if (!empty($widget['vars'])) {
                        foreach ($widget['vars'] as $varName => $var) {
                            $widgetVars[$varName] = $var['value'];
                        }
                    }

                    $widget['vars']       = $widgetVars;
                    $widgets[$widgetName] = $widget;
                }
            }
        }

        return ['vars' => $vars, 'widgets' => $widgets];
    }

    public function checkUserLogin()
    {
        $userId = cmf_get_current_user_id();
        if (empty($userId)) {
            if ($this->request->isAjax()) {
                $this->error("您尚未登录", cmf_url("user/Login/index"));
            } else {
                $this->redirect(cmf_url("user/Login/index"));
            }
        }
    }

}